#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: website.py
@contact: zwb15083976291@163.com
@time: 2021/12/07
"""
from rest_framework import serializers

from common.models import BlogWebInfo, BlogUser
from utils.serializers.serializer import SpecifySerializeFieldModelSerializer, UpdateBaseSerializeMethodMixin


class WebInfoSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        model = BlogWebInfo
        fields = ('id', 'notice', 'website_title', 'website_records')

    def validate_id(self, value):
        if BlogWebInfo.objects.filter(id=value).first():
            return value
        raise serializers.ValidationError("数据不存在")


class UserSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()
    user_image_url = serializers.URLField()
    email = serializers.EmailField()
    github_link = serializers.URLField()
    gitee_link = serializers.URLField()

    class Meta:
        model = BlogUser
        # fields = '__all__'
        exclude = ('create_time', 'update_time', 'password', 'user_type')
        read_only_fields = ('username',)

    def validate_id(self, value):
        if BlogUser.objects.filter(id=value).first():
            return value
        raise serializers.ValidationError("数据不存在")


class UpdatePasswordSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()
    new_password = serializers.CharField()
    confirm_password = serializers.CharField()

    class Meta:
        model = BlogUser
        fields = ('id', 'password', 'new_password', 'confirm_password')

    def validate(self, attrs):
        if attrs.get("new_password") != attrs.get("confirm_password"):
            raise serializers.ValidationError("确认密码错误!")
        user = BlogUser.objects.filter(id=attrs.get("id")).first()
        if not user:
            raise serializers.ValidationError("数据不存在")
        if user.password != attrs.get("password"):
            raise serializers.ValidationError("密码错误")
        self.context['user'] = user
        return attrs
